# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：商品路由
"""
import math
import os
import uuid

from fastapi import APIRouter, UploadFile, HTTPException
from starlette.responses import FileResponse, JSONResponse

from config import settings
from core.Response import base_response
from typing import Union

from curd.good import add_good_curd
from models.base import Goods
from schemas.goods import GoodSchemas, GoodListResponseSchemas, GoodResponseSchemas, GoodAddSchemas
from schemas.base import BaseResponse, DetailBaseResp

good_router = APIRouter(prefix='/goods')


@good_router.post('', summary='新增商品', response_model=Union[GoodResponseSchemas, BaseResponse])
async def good_add(post: GoodAddSchemas):
    try:
        good = await add_good_curd(post)
    except HTTPException as e:
        return base_response(code=str(e).split(":")[0], msg=str(e).split(":")[1])
    except Exception as e:
        return base_response(code=500, msg=f"新增商品失败！失败原因为:{e}")
    return base_response(code=200, msg='新增商品成功！', data=good)


@good_router.get('', summary='商品列表', response_model=GoodListResponseSchemas)
async def good_list(page: int = 1, pageSize: int = 500, query: Union[str, None] = None):
    if query:
        total = await Goods.filter(name__contains=query).all().count()
        items = await Goods.filter(name__contains=query).all().limit(pageSize).offset((page - 1) * pageSize)
    else:
        total = await Goods.all().count()
        items = await Goods.all().limit(pageSize).offset((page - 1) * pageSize)
    data = {
        "page": page,
        "pages": math.ceil(total / pageSize),
        "total": total,
        "data": [GoodSchemas(**dict(item)) for item in items]
    }
    return base_response(code=200, msg='获取商品列表成功！', data=data)


@good_router.delete('/{id}', summary='删除商品', response_model=BaseResponse)
async def good_del(id: int):
    good = await Goods.get_or_none(id=id)
    if not good:
        return base_response(code=422, msg='商品不存在！')
    await good.delete()
    await good.static_attrs.clear()
    await good.dynamic_attrs.clear()
    await good.save()
    return base_response(code=200, msg='商品删除成功！')


@good_router.post('/upload', summary='上传商品图片', response_model=DetailBaseResp)
async def good_upload_image(id: int, file: UploadFile):
    good = await Goods.get_or_none(id=id)
    if not good:
        return base_response(code=422, msg='商品不存在！')
    if file.content_type not in settings.FILE_ALLOWED_EXTENSIONS:
        return base_response(code=422, msg='文件类型错误！只允许上传图片文件！类型为：JPG,JPEG,PNG')
    if file.size > settings.FILE_MAX_FILE_SIZE:
        return base_response(code=422, msg='文件大小超出限制！最大允许上传大小为：4MB')
    new_file_name = str(uuid.uuid4()) + file.filename[file.filename.rfind('.'):]
    file_path = os.path.join(settings.FILE_DIR, new_file_name)
    with open(file_path, 'wb') as f:
        f.write(file.file.read())
    good.big_log = new_file_name
    await good.save()
    return base_response(code=200, msg='商品图片上传成功！', data=dict(good))


@good_router.get('/fileName', summary='访问商品图片', response_model=DetailBaseResp)
async def good_image_get(fileName: str):
    if not os.path.exists(os.path.join(settings.FILE_DIR, fileName)):
        return base_response(code=404, msg='商品图片不存在！')
    # 这种是直接返回一个图片文件
    # return FileResponse(os.path.join(settings.FILE_DIR, fileName))
    image_url = f"http://{settings.APP_HOST}:{settings.APP_PORT}/files/{fileName}"
    return base_response(code=200, msg='商品图片获取成功！', data=image_url)
